//
//  PlayView.swift
//  ShouChong
//
//  Created by yw on 2024/7/26.
//

import SwiftUI

struct PlayView: View {
    @State private var count:Int = 0
    @State var speed:CGFloat = 0.5
    @State private var timer:Timer?
    @State private var isStart:Bool = true
    @State var adVM:InterstitialViewModel = InterstitialViewModel()
    let throttler = Throttler(interval: 0.5)
    var body: some View {
        GeometryReader(content: { geometry in
            ScrollView(showsIndicators: false, content: {
                VStack(content: {
                    LottieCircleView(speed: $speed)
                        .frame(width: 300,height: 300)
                        .overlay(alignment: .center) {
                            countView
                        }.padding(.top,30)
                    Spacer()
                    TimerCalcuteView(count:$count, isStart:$isStart) {
                        startCountAction()
                    } stopBlock: {
                        GyroMannager.shared.stop()
                    }.padding(.bottom,20)

                }).frame(minHeight: geometry.size.height)
                
            })
            .frame(width: geometry.size.width)
            .onAppear {
                startCountAction()
                Task {
                    await adVM.loadAd()
                }
            }
            .onDisappear{
                GyroMannager.shared.resetCount()
                showAD()
            }
        })
        
        
    }
    
    private func showAD() {
        if let isVip = UserDefaults.standard.value(forKey: kVipKey) as? Bool {
            if !isVip {
                let random = arc4random_uniform(3)
                if random == 0 {
                    adVM.showAd()
                }
            }
        } else {
            UserDefaults.standard.setValue(false, forKey: kVipKey)
            let random = arc4random_uniform(3)
            if random == 0 {
                adVM.showAd()
            }
        }
        
    }
    
    var countView:some View {
        VStack {
            Text("\(count)")
                .minimumScaleFactor(0.5)
                .frame(maxWidth: 160)
                .frame(height: 80)
            //                .background(Color.red)
                .lineLimit(0)
                .modifier(MainTextModifier(fontSize: 60, fontWeight: .bold, foreColor: Color("color_text_black")))
            HStack {
                Text("次数")
                    .modifier(MainTextModifier(fontSize: 12, fontWeight: .light, foreColor: Color("color_gray")))
//                ShakeButton(
//                    label:
//                        Image(systemName: "questionmark.circle.fill")
//                        .resizable()
//                        .frame(width: 16,height: 16)
//                        .foregroundColor(Color("color_gray"))
//                        .offset(x: -4)
//                    
//                ) {
//                    let sheetView = SheetTipsView.createSheetTipsView(content: "") {
//                        
//                    }
//                    sheetView.show(.sheet, backgoundTapDismissEnable: false)
//                }
                
            }
            
        }
    }
    
    
    
    private func startCountAction() {
        GyroMannager.shared.start(isPuase: !isStart) { speed in
            
            throttler.throttle {
                self.calcuteSpeed(speed: speed)
            }
        } countBlock: { count in
            
            self.count = count
        }
    }
    
    private func calcuteSpeed(speed:Double) {
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            let slowSpeed = abs(speed - 1)
            if slowSpeed < 0.3 {
                self.speed = 0.5
            } else if slowSpeed >= 0.5 {
                self.speed = speed * 1.3
            } else if slowSpeed >= 0.7 {
                self.speed = speed * 1.6
            } else if slowSpeed >= 1.0 {
                self.speed = speed * 1.9
            } else if slowSpeed >= 2.0 {
                self.speed = speed * 2.1
            } else if slowSpeed >= 3.0 {
                self.speed = speed * 2.4
            }else {
                self.speed = 8
            }
        }
    }
}


struct TimerCalcuteView:View {
    @Binding var count:Int
    // 状态变量，存储计时器的总秒数
    @State private var totalSeconds = 0.0
    // 状态变量，控制计时器是否运行
    @State private var isTimerRunning = false
    // 计时器的引用，用于暂停和恢复
    @State private var timer: Timer?
    @Binding var isStart:Bool
    let timerInterval:Double = 1.0 // 计时器的间隔时间，单位为秒
    var startBlock:() -> Void
    var stopBlock:() -> Void
    var body: some View {
        VStack {
            HStack {
                Spacer()
                VStack {
                    Text("时长")
                        .modifier(MainTextModifier(fontSize: 12, fontWeight: .light, foreColor: Color("color_gray")))
                    Text(formatTime())
                    //                .minimumScaleFactor(0.5)
                    //                .background(Color.red)
                        .lineLimit(0)
                        .modifier(MainTextModifier(fontSize: 40, fontWeight: .bold, foreColor: Color("color_text_black")))
                }
                Spacer()
                Spacer()
                VStack {
                    HStack {
                        Text("心率")
                            .modifier(MainTextModifier(fontSize: 12, fontWeight: .light, foreColor: Color("color_gray")))
                        ShakeButton(
                            label:
                                Image(systemName: "questionmark.circle.fill")
                                .resizable()
                                .frame(width: 16,height: 16)
                                .foregroundColor(Color("color_gray"))
                                .offset(x: -4)
                            
                        ) {
                            let sheetView = SheetTipsView.createSheetTipsView(content: "iPhone端暂时无法实时测量您的心率，如您需要记录心率，请使用iWatch获取") {
                            }
                            sheetView.show(.sheet, backgoundTapDismissEnable: false)
                        }
                    }
                    
                    Text("0")
                    //                .minimumScaleFactor(0.5)
                    //                .background(Color.red)
                        .lineLimit(0)
                        .modifier(MainTextModifier(fontSize: 40, fontWeight: .bold, foreColor: Color("color_text_black")))
                }
                Spacer()
            }
            .padding(.bottom,50)
            buttonHStackView
            
        }.onAppear(perform: {
            startTimer()
        }).onDisappear(perform: {
            resetTimer()
            count = 0
            GyroMannager.shared.resetCount()
        })
    }
    
    var buttonHStackView:some View {
        HStack {
            Spacer()
            ShakeButton(
                label:
                    RoundedRectangle(cornerRadius: 5)
                    .fill(Color("color_text_black").opacity(0.5))
                    .overlay(alignment: .center, content: {
                        Image(systemName: isStart ? "pause.fill":"play.fill")
                            .foregroundColor(Color("color_text_black"))
                    })
            ) {
                
                startAction()
                
            }
            .frame(width: 48,height: 48)
            .offset(x: -6)
            ShakeButton(
                label:
                    RoundedRectangle(cornerRadius: 5)
                    .fill(Color("color_chart_duration_01").opacity(0.3))
                    .overlay(alignment: .center, content: {
                        Image(systemName: "stop.fill")
                            .foregroundColor(Color("color_chart_duration_01").opacity(0.6))
                    })
            ) {
                resetTimer()
                showTipsView()
            }.frame(width: 120,height: 48)
                .offset(x: 6)
            Spacer()
        }
    }
    
    private func startAction() {
        isStart.toggle()
        if isStart {
            startTimer()
        } else {
            pauseTimer()
        }
    }
    
    private func startTimer() {
        timer = Timer.scheduledTimer(withTimeInterval: timerInterval, repeats: true) { _ in
            totalSeconds += timerInterval
        }
        startBlock()
        
    }
    
    private func pauseTimer() {
        
        timer?.invalidate()
        timer = nil
        
        stopBlock()
    }
    
    private func resetTimer() {
        pauseTimer()
        
    }
    
    private func showTipsView() {
        let tipsView = TipsView.createTipsView(title: "提示", content: "是否结束本次运动嘛？") {tag in
            ///结束本次运动
            
            self.uploadUserAction(tag: tag)
        } cancelAction: {
            self.startTimer()
        }
        tipsView.show(.sheet, backgoundTapDismissEnable: false)
    }
    // 格式化时间显示为mm:ss
    private func formatTime() -> String {
        let minutes = Int(totalSeconds) / 60
        let seconds = Int(totalSeconds) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
    
    private func uploadUserAction(tag:Int) {
        let sendData = [
            "count":String(count),
//            "calorie":"0",
            "remark":String(tag),
            "other":"ios",
            "duration":String(Int(totalSeconds)),
            "isWatch":"0",
            "heartRate":"0"
        ]
        DPrint("上传用户使用记录\(sendData)")
        YWNetworkTool.share().requestJson(url: "info/setNNUserHistory", parameters: sendData) { res in
            totalSeconds = 0
            DPrint(res)
//            YWToast.show(text: "用户记录已上传",duration: 0.8)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                NotificationCenter.default.post(name: NSNotification.Name("uploadUserActionNotify"), object: nil)
            }
        } responseFailBlock: { error, code in
            totalSeconds = 0
            DPrint(error)
            YWToast.show(text: "用户记录上传失败",duration: 0.8)
        }
    }
}




///节流类
class Throttler {
    private var lastCallTimestamp: Date?
    private let interval: TimeInterval
    private let queue: DispatchQueue
    
    init(interval: TimeInterval, queue: DispatchQueue = .main) {
        self.interval = interval
        self.queue = queue
    }
    
    func throttle(action: @escaping () -> Void) {
        let now = Date()
        if let lastCall = lastCallTimestamp {
            let delta = now.timeIntervalSince(lastCall)
            if delta < interval {
                // 如果上次调用到当前时间间隔小于期望的节流间隔，不调用函数
                return
            }
        }
        // 更新最后一次调用时间，并在队列中执行函数
        lastCallTimestamp = Date()
        queue.async {
            action()
        }
    }
}
